import request from 'umi-request';

const UserModel = {
  namespace: 'user',
  state: {
    data: '',
  },
  effects: {
    *query({ payload }, { call, put }) {
      request
        .get('http://localhost:8000/api/getlist', {
          params: {
            author: 'songsikai',
          },
        })

        .then(function (response) {
          console.log('response', response);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    *createUser({ payload }, { call, put }) {
      console.log('payload', payload);
      const { name, pwd } = payload;
      request
        .post('http://localhost:8000/api/createUser', {
          params: { name, pwd },
        })

        .then(function (response) {
          console.log('response', response);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
  },
  reducers: {
    get(state, action) {
      const data = [
        {
          key: '1',
          name: 'John Brown',
          age: 32,
          address: 'New York No. 1 Lake Park',
          tags: ['nice', 'developer'],
        },
        {
          key: '2',
          name: 'Jim Green',
          age: 42,
          address: 'London No. 1 Lake Park',
          tags: ['loser'],
        },
        {
          key: '3',
          name: 'Joe Black',
          age: 32,
          address: 'Sidney No. 1 Lake Park',
          tags: ['cool', 'teacher'],
        },
      ];

      return {
        ...state,
        data,
      };
    },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/user') {
          dispatch({
            type: 'get',
          });
        }
      });
    },
  },
};
export default UserModel;
